#include<iostream>
#include<string>
#include<memory>
#include<cstring>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"InetAddr.hpp"
//cs模式
int main(int argc,char* argv[])
{
    if(argc!=3){    
        std::cout<<"Usage: "<<argv[0]<<" <server_ip>  <server_port>"<<std::endl;
        exit(1);
    }
    std::string server_ip=argv[1];//服务器IP地址
    uint16_t server_port=std::stoi(argv[2]);//服务器端口号
    //创建套接字
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0){
        std::cerr<<"create socket error"<<std::endl;
        exit(2);
    }

    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(server_port);
    server_addr.sin_addr.s_addr=::inet_addr(server_ip.c_str());
    // 客户端必须也要有自己的ip地址和端口号，但是客户端不需要自己显示调用bind函数，因为首次发送数据时，系统会自动调用bind函数
    while(true){
        std::cout<<"input message:"<<std::endl;
        std::string message;
        std::getline(std::cin,message);
        //发送数据
        int n = ::sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&server_addr,sizeof(server_addr));
        struct sockaddr_in client_addr;
        socklen_t len = sizeof(client_addr);
        //接收数据
        char recv_buf[1024];
        n = ::recvfrom(sockfd,recv_buf,sizeof(recv_buf)-1,0,(struct sockaddr*)&client_addr,&len);
        if(n>0){
            recv_buf[n]='\0';
            std::cout<<recv_buf<<std::endl;
        }
    }

    return 0;
}